/*
 * @Author: Drc
 * @Date: 2020-11-23 14:07:52
 * @LastEditTime: 2020-12-16 12:00:40
 * @LastEditors: Drc
 */

import json_zh from './zh'
import json_en from './en'
const fs = require('fs')
const prettier = require('prettier')
const outputDir = './src/res/strings/type.ts'
let prettierConfig = {}
//首元素作为默认语言，脚本基于默认语言生成结构，顺序决定代码提示顺序
const originJsonList = [json_zh, json_en]
const separate_symbol = '⭐️⭐️⭐️'

//获取格式化配置信息
async function getPrettierOption() {
  prettierConfig = (await prettier.resolveConfig('.')) ?? {}
}

//创建扁平json
function createflatJson(originJson: any) {
  let flatJson: any = {}

  //将json扁平化
  function tranJsonToFlat(data: any = originJson, keys: string[] = [], recursiveIndex: number = 0) {
    Object.keys(data).map((item: string) => {
      if (typeof data[item] === 'string') {
        //叶子
        keys.splice(keys.length - recursiveIndex, keys.length - recursiveIndex)

        //把key用点语法连接
        let newKey = ''
        keys.map((key) => {
          newKey += `${key}.`
        })
        newKey += item

        flatJson[newKey] = data[item]
      } else {
        //节点
        if (recursiveIndex === 0) {
          keys = []
        }
        keys.push(item)

        tranJsonToFlat(data[item], keys, recursiveIndex + 1)
      }
    })
  }

  //执行
  tranJsonToFlat()
  return flatJson
}

//全语言值拼接，用于提示
function patchAllJsonValue() {
  flatJsonList.map((json, index) => {
    if (index !== 0) {
      for (let outputKey in outputFlatJson) {
        for (let jsonKey in json) {
          if (outputKey === jsonKey) {
            outputFlatJson[outputKey] += ` ${separate_symbol} ${json[jsonKey]}`
            continue
          }
        }
      }
    }
  })
}
//构造参数
function createParam(json: any) {
  let param: any = {}
  Object.keys(json).map((key) => {
    const paramList = getParam(json[key])
    if (Array.isArray(paramList) && paramList.length) {
      param[key] = {}
      paramList.map((item) => {
        param[key][item] = ''
      })
    }
  })
  return param
}

function getParam(template: string, regexp: RegExp = /%{([\s\S]+?)}/g): string[] {
  const res: string[] = []

  while (true) {
    const matches = regexp.exec(template)
    if (!matches) {
      break
    }
    res.push(matches[1].trim())
  }

  return res
}

//批量创建扁平json
const flatJsonList = originJsonList.map((json) => {
  return createflatJson(json)
})
//目标json
const outputFlatJson = flatJsonList[0] ?? {}

//参数对象
const param = createParam(outputFlatJson)

patchAllJsonValue()

//代码格式化
getPrettierOption().finally(() => {
  //内容拼接
  const outputFile = `export default ${JSON.stringify(
    outputFlatJson,
  )} as const \n\n export type string_param = ${JSON.stringify(param).replace(/""/g, 'string')}`
  //格式化
  let prettierJson = prettier.format(outputFile, {...prettierConfig, parser: 'typescript'})
  fs.writeFile(outputDir, prettierJson, (err: any) => {
    if (err) {
      throw new Error(err)
    }
  })
})

export default {}
